package org.dromara.web.websocket;

import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.ClientTypeEnum;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.web.websocket.payload.UserPayloadContent;
import org.dromara.web.websocket.request.UserLoginRequest;
import org.dromara.websocket.connection.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by       PokerFace
 * Create Date      2023-10-04
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */

@Service
public class UserConnectionHolder extends ConnectionHolder {
    private static final Logger logger = LoggerFactory.getLogger(UserConnectionHolder.class);


    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;


    private HashMap<Long, List<Connection>> connections = new HashMap<>();
    private HashMap<Connection, Long> users = new HashMap<>();


    public synchronized void onBind(Connection connection, UserLoginRequest request) {
        LoginUser user = LoginHelper.getLoginUser(request.getToken());
        if (user == null || !ClientTypeEnum.APP.equals(user.getClientKey())) {
            // 未登录或者不是前端用户
            return;
        }
        List<Connection> conn = connections.get(user.getUserId());
        if (conn == null) {
            conn = new ArrayList<>();
            connections.put(user.getUserId(), conn);
        }
        conn.add(connection);
        users.put(connection, user.getUserId());
        logger.debug("Bind User success:" + user.getUserId());
    }


    @Override
    public synchronized void onConnectionRemoved(Connection connection) {
        Long userId = users.remove(connection);
        if (userId != null) {
            List<Connection> conn = connections.get(userId);
            if (CollectionUtils.isNotEmpty(conn)) conn.remove(connection);
        }
    }





}
